const express = require('express');

const path = require('path');

const session = require('express-session');

//引入路由
const userRouter = require('./router/user');

const articleRouter = require('./router/article');

const commentRouter = require('./router/comment');

const app = express();

app.use(express.static('./public'));

app.use(express.urlencoded({
    extended: false
}));

app.use(session({
    secret: 'vBlog', //加密
    resave: false, //强制保存
    saveUninitialized: true, //强制将“未初始化”的会话保存
    cookie: {
        maxAge: 1000 * 60 * 60 * 24 //指定登陆对话的有效时长
    }
}));

//登录拦截
app.use((req, res, next) => {
    let user = req.session.user;
    let path = req.path;
    // console.log('session', user, path);
    if (path !== '/user/login' && path !== '/user/reg' && path !== '/article/') {
        if (!user) {
            res.redirect('/article/');
        } else {
            next();
        }
    } else {
        next();
    }
});

app.use((req, res, next) => {
    res.locals.user = req.session.user; //res.local.user 把数据传送到页面
    next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//挂载路由
app.use('/user', userRouter);

app.use('/article', articleRouter);

app.use('/comment', commentRouter);

module.exports = app;